<!DOCTYPE html>
<!--引入thymeleaf模板引擎-->
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<html>
<head>
    <meta charset="UTF-8">
    <title>中国梦想游-注册页</title>
    <link href="/home/css/style.css" rel="stylesheet" type="text/css"/>
    <link href="/home/css/common.css" rel="stylesheet" type="text/css"/>
    <script type="text/javascript" src="/home/js/jquery-1.9.1.min.js"></script>
    <script type="text/javascript" src="/home/js/vue.js"></script>
    <script type="text/javascript" src="/home/js/axios.js"></script>
    <script type="text/javascript" src="/home/js/config.js"></script>
    <style type="text/css">
        .error-message {
            color: red;
            font-size: 12px;
        }

        .success-message {
            color: green;
            font-size: 12px;
        }

        .code {
            background-color: #FFBBFF;
            display: inline;
            font-family: Arial;
            font-style: italic;
            color: blue;
            font-size: 20px;
            font-weight: bolder;
            width: 90px;
            padding: 2px 5px;
            cursor: pointer;
        }
    </style>
</head>
<body>
<!--引入header.html文件-->
<div th:replace="/home/header.html"></div>

<div class="b_wrap">
    <div class="current"><span>你现在的位置：</span>
        <a href="index.html">首页</a> >
        <a href="font/reg.jsp">用户注册</a>
    </div>
    <div class="regin_w clearfix">
        <div class="regin_con">
            <div class="regin">
                <div class="tab_menu regin_menu">
                    <ul class="regin_ul">
                        <li class="selected">用户注册</li>
                    </ul>
                </div>
                <div class="tab_box">
                    <div class="regin_tw">

                        <form id="register-form">
                            <table width="700" border="0" cellspacing="0" cellpadding="0">
                                <tr>
                                    <td>用户名：</td>
                                    <td><input class="rg_in" type="text" name="username" id="userName" value=""
                                               placeholder="用户名设置后不可修改" v-model="user.username"
                                               @blur="checkUsername">
                                        <div :class="usernameStatus === 'error' ? 'error-message' : usernameStatus === 'success' ? 'success-message' : ''">
                                            {{ usernameMessage }}
                                        </div>
                                    </td>
                                </tr>
                                <tr>
                                    <td>登录密码:</td>
                                    <td><input class="rg_in" type="password" name="password" id="password" value=""
                                               style="padding:5px 8px;font-size: 14px;"
                                               placeholder="6-20位的数字、字母或符号" v-model="user.password"
                                               @blur="checkPassword">
                                        <div :class="passwordStatus === 'error' ? 'error-message' : passwordStatus === 'success' ? 'success-message' : ''">
                                            {{ passwordMessage }}
                                        </div>
                                    </td>
                                </tr>
                                <tr>
                                    <td>确认密码：</td>
                                    <td><input class="rg_in" type="password" name="RePassword" id="RePassword"
                                               style="padding: 5px 8px;font-size: 14px;" value=""
                                               placeholder="与密码一致" v-model="confirmPassword" @blur="checkRepass">
                                        <div :class="confirmPasswordStatus === 'error' ? 'error-message' : confirmPasswordStatus === 'success' ? 'success-message' : ''">
                                            {{ confirmPasswordMessage }}
                                        </div>
                                    </td>
                                </tr>
                                <tr>
                                    <td>姓名：</td>
                                    <td><input class="rg_in" type="text" name="name" id="name"
                                               style="padding: 5px 8px;font-size: 14px;" value=""
                                               placeholder="请输入您的真实姓名" v-model="user.name">
                                    </td>
                                </tr>
                                <tr>
                                    <td>性别：</td>
                                    <td>
                                        <label><input type="radio" name="sex" value="0" v-model="user.sex"> 女</label>
                                        <label><input type="radio" name="sex" value="1" v-model="user.sex"> 男</label>
                                    </td>
                                </tr>
                                <tr>
                                    <td>出生日期：</td>
                                    <td><input class="rg_in" type="date" name="birthday" id="birthday"
                                               style="padding: 5px 8px;font-size: 14px;" value=""
                                               v-model="user.birthday">
                                    </td>
                                </tr>
                                <tr>
                                    <td>手机号码：</td>
                                    <td width="588"><input class="rg_in" type="text" name="phone" id="phone"
                                                           value="" placeholder="11位手机号" v-model="user.phone"
                                                           @blur="checkPhone">
                                        <div :class="phoneStatus === 'error' ? 'error-message' : phoneStatus === 'success' ? 'success-message' : ''">
                                            {{ phoneMessage }}
                                        </div>
                                    </td>
                                </tr>
                                <tr>
                                    <td>电子邮箱：</td>
                                    <td><input class="rg_in" type="text" name="email" id="email" value=""
                                               placeholder="请填写正确邮箱" v-model="user.email" @blur="checkEmail">
                                        <div :class="emailStatus === 'error' ? 'error-message' : emailStatus === 'success' ? 'success-message' : ''">
                                            {{ emailMessage }}
                                        </div>
                                    </td>
                                </tr>
                                <tr>
                                    <td>验 证 码：</td>
                                    <td><input class="rg_yzm" type="text" id="inputCode" value=""
                                               placeholder="与图片一致" v-model="verificationCode" @blur="validateCode">
                                        <div class="code" id="checkCode" @click="createCode">{{ code }}</div>
                                        <a href="#" @click.prevent="createCode">看不清换一张</a>
                                        <span :class="codeStatus === 'error' ? 'error-message' : codeStatus === 'success' ? 'success-message' : ''">{{ codeMessage
                                            }}</span>
                                    </td>
                                </tr>
                                <!-- 添加人脸照片上传区域 -->
                                <tr>
                                    <td>人脸照片：</td>
                                    <td>
                                        <input type="file" id="faceImage" accept="image/*" @change="handleFaceImageUpload" style="margin-bottom: 10px;">
                                        <div id="facePreview" style="width: 120px; height: 150px; display: none; margin: 10px 0 30px 0; padding: 5px; border: 1px solid #e0e0e0; background-color: #f8f8f8; overflow: hidden;">
                                            <img id="previewImg" src="" style="width: 100%; height: 100%; object-fit: contain;">
                                        </div>
                                        <div :class="faceImageStatus === 'error' ? 'error-message' : faceImageStatus === 'success' ? 'success-message' : ''" style="margin-bottom: 10px;">
                                            {{ faceImageMessage }}
                                        </div>
                                    </td>
                                </tr>
                                <!-- 修改表格结构，确保照片预览不影响其他元素 -->
                                <tr>
                                    <td colspan="2">
                                        <input type="checkbox" id="Box" value="" v-model="agreeTerms" style="margin-left: 120px;"> 我已阅读并同意遵守
                                        <a href="service.html">《中国梦想游服务协议》</a>
                                    </td>
                                </tr>
                                <tr>
                                    <td colspan="2" style="text-align: left; padding-left: 120px; padding-top: 10px;">
                                        <input type="button" class="log_b" value="注册" @click="submitForm"/>
                                    </td>
                                </tr>
                            </table>
                        </form>
                    </div>
                    <div class="hide regin_tw"></div>
                </div>
            </div>
        </div>
        <!--右侧文本-->
        <div class="regin_info">
            <p class="if_t"><b>为什么选择中国梦想游</b></p>
            <div>
                <div class="if_tit"><img src="/home/img/dj_01.jpg"> 低价、放心</div>
                <p>低价保证、无零负团费、无特殊附加
                    费、9大出游保障。</p>
            </div>
            <div>
                <div class="if_tit"><img src="/home/img/ff_01.jpg"> 产品丰富</div>
                <p>8万+旅游产品，涵盖跟团、自助、自
                    驾、邮轮、公司游等，总有一款适合您。</p>
            </div>
            <div>
                <div class="if_tit"><img src="/home/img/xx_01.jpg"> 300万游客的选择</div>
                <p>累计服务300万人次，60万真实点评，
                    2万原创游记。</p>
            </div>
            <div>
                <div class="if_tit"><img src="/home/img/fw_01.jpg"> 更多服务</div>
                <p>全国15个出发城市，24小时服务</p>
            </div>
            <center><img src="/home/img/zc_img0.jpg"></center>
        </div>
    </div>
</div>

<!--引入底部footer.html文件-->
<div th:replace="/home/footer"></div>

<script type="text/javascript">
    var register = new Vue({
        el: '#register-form',
        data: {
            user: {
                username: '',
                password: '',
                name: '',
                sex: '0', // 默认女
                birthday: '',
                phone: '',
                email: ''
            },
            confirmPassword: '',
            verificationCode: '',
            agreeTerms: false,
            code: '',
            // 验证状态
            usernameStatus: '',
            usernameMessage: '',
            passwordStatus: '',
            passwordMessage: '',
            confirmPasswordStatus: '',
            confirmPasswordMessage: '',
            phoneStatus: '',
            phoneMessage: '',
            emailStatus: '',
            emailMessage: '',
            codeStatus: '',
            codeMessage: '',
            // 人脸照片相关状态
            faceImage: '',
            faceImageStatus: '',
            faceImageMessage: ''
        },
        mounted: function () {
            this.createCode();
        },
        methods: {
            // 验证用户名
            checkUsername: function () {
                let username = this.user.username;
                if (username.trim() === "") {
                    this.usernameStatus = 'error';
                    this.usernameMessage = "用户名不能为空";
                    return false;
                }
                let usernameRegex = /^[\u4e00-\u9fa5a-zA-Z0-9_-]{2,16}$/;
                if (!usernameRegex.test(username)) {
                    this.usernameStatus = 'error';
                    this.usernameMessage = "用户名只能是2-16位数字、字母下划线和减号组成";
                    return false;
                }

                // 发送Ajax请求检查用户名是否已存在
                axios.get("/home/checkUserName", {
                    params: {"username": username}
                }).then(response => {
                    if (response.data.code === 200) {
                        this.usernameStatus = 'error';
                        this.usernameMessage = "用户名已经存在，不能重复注册";
                    } else {
                        this.usernameStatus = 'success';
                        this.usernameMessage = "√";
                    }
                }).catch(error => {
                    console.error("检查用户名失败:", error);
                    alert("网络错误，请刷新试一试");
                });
                return true;
            },

            // 验证密码
            checkPassword: function () {
                let password = this.user.password;
                if (password === "") {
                    this.passwordStatus = 'error';
                    this.passwordMessage = "密码不能为空";
                    return false;
                }
                let passwordRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{6,16}$/;
                if (!passwordRegex.test(password)) {
                    this.passwordStatus = 'error';
                    this.passwordMessage = "密码为6-16位字符,必须包含大小写字母和数字";
                    return false;
                } else {
                    this.passwordStatus = 'success';
                    this.passwordMessage = "√";
                }
                return true;
            },

            // 验证确认密码
            checkRepass: function () {
                let pass1 = this.user.password;
                let pass2 = this.confirmPassword;
                if (pass2 === "") {
                    this.confirmPasswordStatus = 'error';
                    this.confirmPasswordMessage = "请输入确认密码！";
                    return false;
                }
                if (pass1 !== pass2) {
                    this.confirmPasswordStatus = 'error';
                    this.confirmPasswordMessage = "密码与确认密码不同！";
                    return false;
                } else {
                    this.confirmPasswordStatus = 'success';
                    this.confirmPasswordMessage = "√";
                }
                return true;
            },

            // 验证手机号
            checkPhone: function () {
                let phone = this.user.phone;
                if (phone.trim() === "") {
                    this.phoneStatus = 'error';
                    this.phoneMessage = "手机号不能为空";
                    return false;
                }
                let phoneRegex = /^1[3456789]\d{9}$/;
                if (!phoneRegex.test(phone)) {
                    this.phoneStatus = 'error';
                    this.phoneMessage = "手机号格式错误";
                    return false;
                }

                // 发送Ajax请求检查手机号是否已存在
                axios.get("/home/checkPhone", {
                    params: {"phone": phone}
                }).then(response => {
                    if (response.data.code === 200) {
                        this.phoneStatus = 'error';
                        this.phoneMessage = "该手机号已经注册过了！";
                    } else {
                        this.phoneStatus = 'success';
                        this.phoneMessage = "√";
                    }
                }).catch(error => {
                    console.error("检查手机号失败:", error);
                    alert("网络错误，请刷新试一试");
                });
                return true;
            },

            // 验证邮箱
            checkEmail: function () {
                let email = this.user.email;
                if (email.trim() === "") {
                    this.emailStatus = 'error';
                    this.emailMessage = "邮箱不能为空";
                    return false;
                }
                let emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
                if (!emailRegex.test(email)) {
                    this.emailStatus = 'error';
                    this.emailMessage = "邮箱格式错误！";
                    return false;
                }

                // 发送Ajax请求检查邮箱是否已存在
                axios.get("/home/checkEmail", {
                    params: {"email": email}
                }).then(response => {
                    if (response.data.code === 200) {
                        this.emailStatus = 'error';
                        this.emailMessage = "该邮箱已经存在！";
                    } else {
                        this.emailStatus = 'success';
                        this.emailMessage = "√";
                    }
                }).catch(error => {
                    console.error("检查邮箱失败:", error);
                    alert("网络错误，请刷新试一试");
                });
                return true;
            },

            // 生成验证码
            createCode: function () {
                this.code = "";
                let codeLength = 6;
                let codeChars = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
                    'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
                    'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
                for (let i = 0; i < codeLength; i++) {
                    let charNum = Math.floor(Math.random() * 52);
                    this.code += codeChars[charNum];
                }
                // 重置验证码状态
                this.codeStatus = '';
                this.codeMessage = '';
            },

            // 验证验证码
            validateCode: function () {
                if (this.verificationCode.length <= 0) {
                    this.codeStatus = 'error';
                    this.codeMessage = "请输入验证码";
                } else if (this.verificationCode.toUpperCase() != this.code.toUpperCase()) {
                    this.codeStatus = 'error';
                    this.codeMessage = "验证码错误";
                    this.createCode();
                } else {
                    this.codeStatus = 'success';
                    this.codeMessage = "验证码正确";
                }
            },
            // 处理人脸照片上传
            handleFaceImageUpload: function (event) {
                const file = event.target.files[0];
                if (!file) {
                    this.faceImageStatus = 'error';
                    this.faceImageMessage = '请选择一张照片';
                    return;
                }

                // 检查文件类型
                const isImage = file.type.startsWith('image/');
                if (!isImage) {
                    this.faceImageStatus = 'error';
                    this.faceImageMessage = '请选择有效的图片文件';
                    return;
                }

                // 检查文件大小（限制2MB）
                const isLt2M = file.size / 1024 / 1024 < 2;
                if (!isLt2M) {
                    this.faceImageStatus = 'error';
                    this.faceImageMessage = '图片必须小于2MB';
                    return;
                }

                // 显示预览
                const reader = new FileReader();
                const preview = document.getElementById('facePreview');
                const previewImg = document.getElementById('previewImg');

                const vm = this; // 保存Vue实例引用
                reader.onload = function (e) {
                    preview.style.display = 'block';
                    previewImg.src = e.target.result;
                    // 保存Base64编码（去掉前缀）
                    vm.faceImage = e.target.result.split(',')[1];
                    vm.faceImageStatus = 'success';
                    vm.faceImageMessage = '照片上传成功';
                }

                reader.readAsDataURL(file);
            },
            // 调用后端进行人脸注册
            registerFace: function (userId, shouldRedirect = false) {
                if (!this.faceImage) {
                    console.log('没有上传人脸照片，跳过人脸注册');
                    if (shouldRedirect) {
                        alert("注册成功！请回到登陆界面登录");
                        window.location.href = "/home/login.html";
                    }
                    return;
                }

                // 构建请求数据
                const faceData = {
                    image: this.faceImage,
                    userInfo: this.user.name,
                    userId: userId,
                    groupId: 'login_face_1' // 这里可以根据实际需求修改用户组
                };

                console.log('发送人脸注册请求:', faceData);

                // 发送人脸注册请求到后端
                axios.post('/home/faceRegister', faceData).then(response => {
                    console.log('人脸注册响应:', response.data);
                    if (response.data.code === 200) {
                        console.log('人脸注册成功:', response.data);
                        if (shouldRedirect) {
                            alert("注册成功！人脸信息已添加，请回到登陆界面登录");
                            window.location.href = "/home/login.html";
                        }
                    } else {
                        console.log('人脸注册失败:', response.data.message);
                        // 人脸注册失败不影响用户注册结果
                        if (shouldRedirect) {
                            alert("注册成功！但人脸信息添加失败，请稍后在个人中心重新添加人脸信息");
                            window.location.href = "/home/login.html";
                        }
                    }
                }).catch(error => {
                    console.error('人脸注册请求失败:', error);
                    if (shouldRedirect) {
                        alert("注册成功！但人脸信息添加失败，请稍后在个人中心重新添加人脸信息");
                        window.location.href = "/home/login.html";
                    }
                });
            }
            ,
            // 在 methods 中添加生日格式化方法
            formatBirthday: function (birthday) {
                if (!birthday) {
                    return '';
                }
                // 检查是否已经是 YYYY-MM-DD 格式的字符串
                if (typeof birthday === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(birthday)) {
                    return birthday;
                }
                // 处理 Date 对象或其他格式
                const date = new Date(birthday);
                const year = date.getFullYear();
                const month = String(date.getMonth() + 1).padStart(2, '0');
                const day = String(date.getDate()).padStart(2, '0');
                return `${year}-${month}-${day}`;
            },

            // 提交表单
            // 提交表单
            submitForm: function () {
                // 执行所有验证
                let isUsernameValid = this.checkUsername();
                let isPasswordValid = this.checkPassword();
                let isConfirmPasswordValid = this.checkRepass();
                let isPhoneValid = this.checkPhone();
                let isEmailValid = this.checkEmail();
                this.validateCode();

                // 短暂延迟以等待异步验证完成
                setTimeout(() => {
                    if (isUsernameValid && isPasswordValid && isConfirmPasswordValid &&
                        isPhoneValid && isEmailValid && this.codeStatus === 'success') {

                        if (!this.agreeTerms) {
                            alert("请先阅读并勾选注册协议！");
                            return;
                        }

                        if (confirm("确认要提交么？")) {
                            // 构建用户数据对象
                            const userData = {
                                username: this.user.username,
                                password: this.user.password,
                                name: this.user.name,
                                sex: parseInt(this.user.sex),
                                // 修复生日格式 - 将生日转换为 YYYY-MM-DD 格式字符串
                                birthday: this.formatBirthday(this.user.birthday),
                                phone: this.user.phone,
                                email: this.user.email
                            };

                            console.log("提交的用户数据:", userData);

                            // 发送注册请求
                            axios.post("/home/register", userData).then(response => {
                                console.log(response.data);
                                if (response.data.code === 200) {
                                    // 确保获取正确的用户ID（数字类型）
                                    const userId = response.data.data.userId;

                                    if (!userId) {
                                        console.error('未获取到用户ID，无法进行人脸注册');
                                        alert("注册成功！请回到登陆界面登录");
                                        window.location.href = "/home/login.html";
                                        return;
                                    }

                                    // 调用人脸注册，确保在人脸注册完成后再跳转
                                    this.registerFace(userId, true);
                                } else {
                                    alert(response.data.message);
                                }
                            }).catch(error => {
                                console.error("注册失败:", error);
                                alert("注册失败，请稍后再试");
                            });
                        } else {
                            alert("您取消了注册信息的提交！！");
                        }
                    } else {
                        alert("信息验证不通过，请返回重新填写！！");
                    }
                }, 500);
            }
        }
    });
</script>
</body>
</html>





